package com.yale.user.controller;

import com.google.common.base.Strings;
import com.yale.spring.cloud.commons.OpenResponse;
import com.yale.spring.cloud.commons.OpenResponseCode;
import com.yale.spring.cloud.commons.constants.CommonConstants;
import com.yale.spring.cloud.feigin.api.CodeService;
import com.yale.user.entity.User;
import com.yale.user.service.UserService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @author yale
 */
@Controller
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    @DubboReference
    private CodeService codeService;

    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("/")
    public String index(){
        return "login";
    }


    @GetMapping("/login/{mail}/{password}")
    @ResponseBody
    public OpenResponse login(HttpServletResponse response, @PathVariable String mail, @PathVariable String password){
        User userFind = userService.findByMailAndPassword(mail, password);

        if(userFind!=null){
            String token = UUID.randomUUID().toString().replaceAll("-","");
            response.addHeader(CommonConstants.TOKEN,token);
            Cookie cookie = new Cookie(CommonConstants.TOKEN, token);
            cookie.setPath("/");
            cookie.setMaxAge(7 * 24 * 60 * 60);
            response.addCookie(cookie);
            redisTemplate.opsForValue().set(token,mail);
            return new OpenResponse();
        }else{
            return new OpenResponse(OpenResponseCode.FAILED);
        }

    }

    @GetMapping("/register/{mail}/{password}/{code}")
    @ResponseBody
    public OpenResponse register(@PathVariable String mail,@PathVariable String password,@PathVariable String code){
        User userFind = userService.findByMail(mail);
        if(userFind!=null){
            return new OpenResponse(OpenResponseCode.FAILED);
        }else{
            User user=new User();
            user.setMail(mail);
            user.setPassword(password);
            userService.save(user);
            return new OpenResponse();
        }
    }


    @GetMapping("/verifyCode/{mail}/{code}")
    @ResponseBody
    public boolean verifyCode(@PathVariable String mail,@PathVariable String code){
        return codeService.verifyCode(mail, code);
    }

    @GetMapping("/welcome/{mail}")
    @ResponseBody
    public String welcome(@PathVariable String mail){
        return mail;
    }
}
